
<div class="layuimini-container layuimini-page-anim">
    <div class="layuimini-main">

        <form class="layui-form" action="" lay-filter="formExample">


            <div class="layui-form-item">
                <label class="layui-form-label"><span style="color: red;">*</span>权限组名称</label>
                <div class="layui-input-inline">
                    <input type="text" name="name" lay-verify="required"  autocomplete="off" class="layui-input">
                </div>
                <div class="layui-form-mid layui-word-aux"></div>
            </div>

            <div class="layui-form-item" hidden>
                <label class="layui-form-label">权限组ID</label>
                <div class="layui-input-inline">
                    <input type="text" name="id" id='id' class="layui-input">
                </div>
            </div>

            <div class="layui-form-item">
                <label class="layui-form-label">归属部门</label>
                <div class="layui-input-inline">
                    <input type="text" name="departmentMember" id="departmentMember" readonly  autocomplete="off" class="layui-input">
                </div>
                <div class="layui-form-mid layui-word-aux"></div>
            </div>

            <div class="layui-form-item" hidden>
                <label class="layui-form-label">部门成员ID</label>
                <div class="layui-input-inline">
                    <input type="text" name="departmentMemberID" id="departmentMemberID"  autocomplete="off" class="layui-input">
                </div>
                <div class="layui-form-mid layui-word-aux"></div>
            </div>

            <div class="layui-form-item">
                <label class="layui-form-label">归属用户</label>
                <div class="layui-input-inline">
                    <input type="text" name="userMember" id="userMember" readonly  autocomplete="off" class="layui-input" ts-selected="">
                </div>
                <div class="layui-form-mid layui-word-aux"></div>
            </div>

            <div class="layui-form-item" hidden>
                <label class="layui-form-label">用户成员ID</label>
                <div class="layui-input-inline">
                    <input type="text" name="userMemberID" id="userMemberID"  autocomplete="off" class="layui-input">
                </div>
                <div class="layui-form-mid layui-word-aux"></div>
            </div>

          
            <div id="view"></div>


            

            <div class="layui-form-item">
                <div class="layui-input-block">
                    <button class="layui-btn" lay-submit="" lay-filter="demo1">确定</button>
                </div>
            </div>
        </form>



    </div>
</div>


<script type="text/html" id="demo">

    {{# if(d.permissionGroupType!="fun" || d==undefined){ }}
    <div class="layui-form-item">
        <label class="layui-form-label">数据权限</label>
        <div class="layui-input-inline">
            <input type="text" name="dataPermission" placeholder="点击查看" readonly="readonly" autocomplete="off" class="layui-input" id="dataPermission" value="">
        </div>
    </div>
    {{# } else { }}
     
    {{# } }}

</script>

<script>

    



    layui.use(['form', 'layedit', 'laydate','tree','tableSelect','laytpl'], function () {
        var form = layui.form
            , layer = layui.layer
            , layedit = layui.layedit
            , tree = layui.tree
            , laydate = layui.laydate
            , table = layui.table
            , laytpl = layui.laytpl
            , tableSelect = layui.tableSelect;


        /**
         * 初始化表单，要加上，不然刷新部分组件可能会不加载
         */
        form.render();


        /**
        *模板渲染可能不会显示的"数据权限"模块
        */
        var data = data_permissionMgt;
        if (data == undefined) {
            data = []
        }
        var getTpl = demo.innerHTML
            , view = document.getElementById('view');
        laytpl(getTpl).render(data, function (html) {
            view.innerHTML = html;
        });


        //自定义验证规则
        form.verify({
            title: function (value) {
                if (value.length < 5) {
                    return '标题至少得5个字符啊';
                }
            }
            , pass: [
                /^[\S]{6,12}$/
                , '密码必须6到12位，且不能出现空格'
            ]
            , content: function (value) {
                layedit.sync(editIndex);
            }
        });


        //表单初始赋值
        /*data_userMgr是从userMgr页面传递过来的*/
        if (data_permissionMgt) {
            //id输入框不可用
            $("#name").attr("disabled","disabled");

            //赋值
            form.val('formExample', {
            "name": data_permissionMgt.permissionGroupName
            ,"id":data_permissionMgt.permissionGroupID
             
            , "departmentMember":data_permissionMgt.showDepartments
            , "departmentMemberID": data_permissionMgt.departments
            , "userMember": data_permissionMgt.showUsers
            , "userMemberID": data_permissionMgt.users


            // , "interest": 1
            // , "like[write]": true //复选框选中状态
            // , "close": true //开关状态
            // , "sex": "女"
            // , "desc": "我爱 layui"
        })
            $("#userMember").attr("ts-selected",data_permissionMgt.users.replace(new RegExp(";","gm"), ","))

        }
        
   //监听提交
   form.on('submit(demo1)', function (data) {
            if (data_permissionMgt){
                data.field["type"] = "edit"
            }else{
                data.field["type"] = "add"
            }
            data.field["newDataPermission"]=dataPermissionList.join(";")
            
            shared.ajaxPost('/adminPermission/addeditPermissionGroup', data.field, function (res) {
            if (res) {
                layer.msg(res, {
                    icon: 1,
                time: 1000 //2秒关闭（如果不配置，默认是3秒）
                }, function(){
                    layer.closeAll();
                });
            }
        })
        return false;
    })
    

        /*
        点击部门成员,触发弹框,进行部门成员选择      
        */
        $("#departmentMember").on("click", function () {
        var content = layui.miniPage.getHrefContent('mypages/usual/permissionMgt/chooseDepartment.html');
        var openWH = layui.miniPage.getOpenWidthHeight();
        //不能用 var 前缀
        opreatType = "add";
        var index = layer.open({
            title: '选择部门成员',
            type: 1,
            shade: 0.2,
            // shade: [0.8, '#393D49'],//底层遮罩样式
            maxmin: true,
            shadeClose: true,
            offset: '100px',
            // area : [ 'auto', '448px' ],
            area : [ '500px', '500px' ],
            // area: [openWH[0] / 2 + 'px', openWH[1] / 2 - 30 + 'px'],
            // offset: [openWH[2] + 'px', openWH[3] + 'px'],
            content: content,
            end: function () {
                // tempList = []
                // var treeObj = $.fn.zTree.getZTreeObj("tree");
                // var nodes = treeObj.getNodes();
                //  rec(nodes);
                // console.log(tempList)
            }
        });
        $(window).on("resize", function () {
            layer.full(index);
        });
        return false;
    });




    /*
    ajax获取当前权限组id,查询该权限组具有的权限
    用于初始化数据权限数结构的需要被勾选的内容
    */
    shared.ajaxGet('/adminPermission/getPermissionTreeExisted', { permissionGroupID: $('#id').val() }, function (res) {
        var tempData = res.data
        dataPermissionList = []
        //["JZCG_METADATA","JZQBZS_METADATA-DZ","JZQBZS_METADATA-FK-P"]
        for (let index = 0; index < tempData.length; index++) {
            const element = tempData[index];

            if (element.type == 0) {
                dataPermissionList.push(element.dbCode)
            }
            else if (element.type == 1) {
                dataPermissionList.push(element.dbCode + "-" + element.field)
            }
            else if (element.type == 2) {
                dataPermissionList.push(element.dbCode + "-" + element.field + "-" + element.pd)
            }
        }
    })



    /*
    点击数据权限,触发弹框,进行数据权限选择 
    */
    $("#dataPermission").on("click", function () {
        var content = layui.miniPage.getHrefContent('mypages/usual/permissionMgt/chooseDataPermission.html');
        var openWH = layui.miniPage.getOpenWidthHeight();
        //不能用 var 前缀
        opreatType = "add";
        var index = layer.open({
            title: '选择数据权限',
            type: 1,
            shade: 0.2,
            // shade: [0.8, '#393D49'],//底层遮罩样式
            maxmin: true,
            shadeClose: true,
            offset: '100px',
            // area : [ 'auto', '448px' ],
            area : [ '500px', '500px' ],
            // area: [openWH[0] / 2 + 'px', openWH[1] / 2 - 30 + 'px'],
            // offset: [openWH[2] + 'px', openWH[3] + 'px'],
            content: content,
            end: function () {
                // dataPermissionList = []
                // var treeObj = $.fn.zTree.getZTreeObj("tree");
                // var nodes = treeObj.getNodes();
                //  rec(nodes);
                // console.log(tempList)
            }
        });
        $(window).on("resize", function () {
            layer.full(index);
        });
        return false;
    });


    /*
    选择用户成员的组件
    */
    tableSelect.render({
            elem: '#userMember',
            searchKey: 'user',
            checkedKey: 'id',
            checkedNameKey:'name',
            searchPlaceholder: '输入用户名或ID',
            showSwitch:1,
            table: {
                url: config.server + "/adminPermission/getuser",
                cols: [[
                    { type: 'checkbox' },
                    { align: 'center', title: '序号', type: 'numbers', width: 50 },
                    { field: 'id', title: 'ID', width: 140 },
                    { field: 'name', title: '姓名', width: 140 },
                    { field: 'showDepartment', title: '部门', width: 140 }
                ]],
                limits:[6,10,20],
                headers: {
                    token: shared.getCookie('token'),
                },
                limit: 6
            },
            done: function (elem, data) {
                idList = []
                nameList = []
                for (let index = 0; index < data.data.length; index++) {
                    const element = data.data[index];
                    idList.push(element.id)
                    nameList.push(element.name)
                }
                elem.val(nameList.join(";"))
                $("#userMemberID").val(idList.join(";"))
            }
        })


    })

        
   
    

  
</script>